from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Optional
import uuid
import datetime

app = FastAPI(
    title="FastMCP API",
    description="Model Context Protocol Management System",
    version="1.0.0"
)

# 内存数据库 (生产环境替换为真实数据库)
prompts_db = {}
templates_db = {}


class PromptTemplate(BaseModel):
    name: str
    content: str
    variables: List[str] = []
    description: Optional[str] = None


class GeneratedPrompt(BaseModel):
    id: str
    template_id: str
    variables: Dict[str, str]
    content: str
    timestamp: datetime.datetime


@app.post("/templates/", response_model=dict)
def create_template(template: PromptTemplate):
    """创建新提示模板"""
    template_id = str(uuid.uuid4())
    templates_db[template_id] = template.dict()
    return {"id": template_id, **template.dict()}


@app.get("/templates/", response_model=List[dict])
def list_templates():
    """列出所有模板"""
    return [{"id": k, **v} for k, v in templates_db.items()]


@app.post("/prompts/generate", response_model=GeneratedPrompt)
def generate_prompt(template_id: str, variables: Dict[str, str]):
    """根据模板生成提示"""
    if template_id not in templates_db:
        raise HTTPException(status_code=404, detail="Template not found")

    template = templates_db[template_id]
    content = template["content"]

    # 替换变量
    for key, value in variables.items():
        content = content.replace(f"{{{key}}}", value)

    # 创建提示记录
    prompt_id = str(uuid.uuid4())
    prompt = GeneratedPrompt(
        id=prompt_id,
        template_id=template_id,
        variables=variables,
        content=content,
        timestamp=datetime.datetime.utcnow()
    )

    prompts_db[prompt_id] = prompt.dict()
    return prompt


@app.get("/prompts/{prompt_id}", response_model=GeneratedPrompt)
def get_prompt(prompt_id: str):
    """获取生成的提示"""
    if prompt_id not in prompts_db:
        raise HTTPException(status_code=404, detail="Prompt not found")
    return prompts_db[prompt_id]


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)